package com.aboverock.module.shiro.service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;

import com.aboverock.module.system.domain.AppKey;
import com.aboverock.module.system.service.AppKeyService;

/**
 * @author Rock Wang
 */
public class AppKeyShiroFilter extends AccessControlFilter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private AppKeyService appKeyService;

    public AppKeyShiroFilter(AppKeyService appKeyService) {
        super();
        this.appKeyService = appKeyService;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        String appKeyParam = request.getParameter("appKey");
        if (StringUtils.isBlank(appKeyParam)) {
            logger.debug("Data-Smart: request中未包含 appKey");
            return false;
        }

        AppKey appKey = appKeyService.getByAppKey(appKeyParam);
        if (appKey == null || appKey.getEnabled() == 0) {
            logger.info("Data-Smart: appKey 不存在或者无效");
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        logger.info("Data-Smart: App Key 验证失败");
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setStatus(HttpStatus.UNAUTHORIZED.value());
        resp.getOutputStream().write("appKey 不存在或者无效".getBytes(StandardCharsets.UTF_8));
        return false;
    }
}
